import axios from 'axios';
import store from '@/store';
import {getCookies} from "@/utils/cookies";

const service = axios.create({
    baseURL: '/api/',
    timeout: 3000
});

// request interceptor
service.interceptors.request.use(
    config => {
        config.headers['Authorization'] = 'Bearer '+store.state.user.access_token;
        console.log('axios.interceptors.request token:',store.state.user.access_token);
        return config;
    },
    error => {
        console.error(error);
        Promise.reject(error);
    }
);

// response interceptor
service.interceptors.response.use(
    res => {
        //console.log('axios.interceptors.response>res:',res);
        if(0==res.data.code)return res;

        console.warn('Token 过期');
        if(getCookies()){//登录状态
            console.log('登录状态');
            if(1==res.data.code){//access_token过期
                store.dispatch('user/refreshToken');
            }
        }else{
            console.log('未登录状态');
            console.log('axios.interceptors.response:0!=res.data.code');
            store.dispatch('user/signOut');
        }
        return Promise.reject(res.data.msg||'Access_Token 已经过期');
    },
    error => {
        Promise.reject(error);
    }
);

export default service;